<template>
  <div>
    <i-row style="height: 50px;">
      <i-col span="20">
        班级条件：
        <i-select style="width: 100px;" v-model="searchWeek" @on-change="search">
          <i-option v-for="week in weeks" :value="week.value" :key="week.value">{{week.label}}</i-option>
        </i-select>
        <i-input-number :max="255" :min="0" v-model="searchNum" @on-change="search"></i-input-number>
      </i-col>
      <i-col span="4">
        <i-button type="primary" icon="ios-arrow-back" style="width:50px;" @click="backwardShift"></i-button>
        <span>{{currentString}}</span>
        <i-button type="primary" icon="ios-arrow-forward" style="width:50px;" @click="forwardShift"></i-button>
      </i-col>
    </i-row>
    <i-row>
      <i-col span="24">
        <i-table border height="600" :columns="columns" :data="viewData.attendanceList"></i-table>
      </i-col>
    </i-row>
  </div>
</template>

<script>
import common from "@/common";

export default {
  name: "attendance-management",
  data: function() {
    return {
      searchWeek: 0,
      searchNum: 1,
      shift: 0,
      weeks: [
        {
          value: 0,
          label: "周日班"
        },
        {
          value: 1,
          label: "周一班"
        },
        {
          value: 2,
          label: "周二班"
        },
        {
          value: 3,
          label: "周三班"
        },
        {
          value: 4,
          label: "周四班"
        },
        {
          value: 5,
          label: "周五班"
        },
        {
          value: 6,
          label: "周六班"
        }
      ],
      columns: [
        {
          title: "学号",
          ellipsis: true,
          render: (h, params) => {
            return h("span", params.row.classHourInfo.code);
          }
        },
        {
          title: "姓名",
          ellipsis: true,
          render: (h, params) => {
            return h("span", params.row.classHourInfo.name);
          }
        },
        {
          title: "总课时",
          align: "center",
          ellipsis: true,
          render: (h, params) => {
            return h(
              "span",
              this.formatClassHour(params.row.classHourInfo.totalClassHour)
            );
          }
        },
        {
          title: "剩余课时",
          align: "center",
          ellipsis: true,
          render: (h, params) => {
            const remainClassHour =
              params.row.classHourInfo.totalClassHour -
              params.row.classHourInfo.usedClassHour;
            return h(
              "div",
              {
                class: {
                  "remain-class-hour-prompt": remainClassHour <= 8,
                  "remain-class-hour-leak": remainClassHour <= 4
                }
              },
              this.formatClassHour(remainClassHour)
            );
          }
        }
      ],
      viewData: []
    };
  },
  created() {
    this.search();
  },
  computed: {
    current() {
      const current = new Date();
      // 移动当前日期到未来最近的一个和检索星期匹配的日期
      if (this.searchWeek >= current.getDay()) {
        current.setDate(
          current.getDate() + (this.searchWeek - current.getDay())
        );
      } else {
        current.setDate(
          current.getDate() + (7 + (this.searchWeek - current.getDay()))
        );
      }
      current.setDate(current.getDate() + 7 * this.shift);
      return current;
    },
    currentString() {
      return common.formatTitle(this.current);
    }
  },
  methods: {
    search() {
      // 清除上次动态添加的列
      this.columns.splice(4, this.columns.length - 4);

      for (let i = -11; i < 1; i++) {
        const current = new Date(this.current);
        // 移动当前日期到过去的11周~未来1周
        current.setDate(current.getDate() + i * 7);

        this.columns[this.columns.length] = {
          title: common.formatTitle(current),
          align: "center",
          width: 70,
          render: (h, params) => {
            let attendanceId = 0;
            for (let index in params.row.attendanceInfo) {
              if (
                common.isSameDay(
                  new Date(params.row.attendanceInfo[index].courseDate),
                  current
                )
              ) {
                attendanceId = params.row.attendanceInfo[index].id;
                break;
              }
            }

            const remainClassHour =
              params.row.classHourInfo.totalClassHour -
              params.row.classHourInfo.usedClassHour;

            return h("Button", {
              props: {
                type: attendanceId > 0 ? "primary" : "ghost",
                icon: attendanceId > 0 ? "checkmark" : "ios-circle-outline",
                size: "small",
                shape: "circle",
                disabled: attendanceId <= 0 && remainClassHour <= 0
              },
              style: {
                display: this.isHoliday(current) ? "none" : ""
              },
              on: {
                click: () => {
                  this.toggleAttendance(
                    attendanceId,
                    params.row.classHourInfo.id,
                    current
                  );
                }
              }
            });
          }
        };
      }

      this.axios
        .get(
          "/attendances/week/" +
            this.searchWeek +
            "/num/" +
            this.searchNum +
            "?shift=" +
            this.shift
        )
        .then(response => {
          if (response.code === 0) {
            this.viewData = response.data;
          } else {
            this.$Message.error("获取考勤信息失败。" + response.message);
          }
        });
    },
    backwardShift() {
      this.shift--;
      this.search();
    },
    forwardShift() {
      this.shift++;
      this.search();
    },
    toggleAttendance(attendanceId, studentId, courseDate) {
      if (attendanceId > 0) {
        this.axios.delete("/attendances/" + attendanceId).then(response => {
          if (response.code === 0) {
            this.$Message.success("取消签到成功。");
            this.search();
          } else {
            this.$Message.error("取消签到失败。" + response.message);
          }
        });
      } else {
        const attendance = {
          studentId: studentId,
          courseDate:
            "" +
            courseDate.getFullYear() +
            "-" +
            (courseDate.getMonth() + 1) +
            "-" +
            courseDate.getDate(),
          operateDate: new Date()
        };
        this.axios.post("/attendances", attendance).then(response => {
          if (response.code === 0) {
            this.$Message.success("签到成功。");
            this.search();
          } else {
            this.$Message.error("签到失败。" + response.message);
          }
        });
      }
    },
    isHoliday(day) {
      let found = false;
      for (let index in this.viewData.holidayInfo) {
        if (
          common.isSameDay(
            new Date(this.viewData.holidayInfo[index].holiday),
            day
          )
        ) {
          found = true;
          break;
        }
      }
      return found;
    },
    formatClassHour(classHour) {
      return common.formatClassHour(classHour);
    }
  }
};
</script>

<style>
/*TODO: How to change to scoped*/
.ivu-table td.holiday-column {
  background-color: #bbbec4;
}

.ivu-table .remain-class-hour-prompt {
  color: #fff;
  background-color: #ff9900;
}

.ivu-table .remain-class-hour-leak {
  color: #fff;
  background-color: #ed3f14;
}
</style>
